﻿using System;
using System.Collections;
using System.Collections.Generic;

namespace DashFire
{
  public class ResUpdateSystem
  {
    #region 单例
    public static ResUpdateSystem Instance { get { return sInstance; } }
    private static ResUpdateSystem sInstance = new ResUpdateSystem();
    private ResUpdateSystem() { }
    #endregion

    public void Init()
    {
      ResUpdateChecker.Instance.URL = "http://192.168.2.149/download.php?filename=AssetBundlesAssetInfo.xml";
      InitDownAddress();

      PathUtil.CreatePersistentDataPath();
    }

    public void StartUpdate()
    {
      ResUpdateMessage.Instance.Log("StartUpdate");
      CoroutineProxy.Instance.StartCoroutine(UpdateCoroutine());
    }

    private IEnumerator UpdateCoroutine()
    {
      ResUpdateMessage.Instance.Log("StartCheck");
      yield return ResUpdateChecker.Instance.StartCheck();

      var listFile = ResUpdateChecker.Instance.GetNeedUpdateFileList();
      if(listFile.Count == 0)
      {
        ResUpdateMessage.Instance.Log("Donot need Update");
        ResUpdateMessage.Instance.SendFinishMessage(0);
        yield break;  //不需要更新
      }

      ResUpdateMessage.Instance.SendMessage(
        ResUpdateMessage.MT.DownLoadFileCount, listFile.Count, string.Empty);
      ResUpdateMessage.Instance.Log("Start DonwLoad File,Count = {0}", listFile.Count);
      DownLoaderManager.Instance.StartDownLoad(listFile);
    }

    private void InitDownAddress()
    {
      DownLoaderManager.Instance.URL = "http://192.168.2.149/download.php?filename=";
    }

    public ResUpdateMessage.Listen Listener {
      get { return ResUpdateMessage.Instance.Listener; }
      set { ResUpdateMessage.Instance.Listener = value; }
    }
  }
}
